var criteriaTypes = [1, 2, 3, 5, 6, 7, 8, 9, 10, 16, 17];

var collections = [
    db.OldTemplateCriteria,
    db.TemplateCriteria,
    db.FilterCriteria,
];

function getCriteriaEntityField(item) {
    return item.Name.replace(/\./g, '');
}

collections.forEach(function (collection) {
    collection.find({ CriteriaType: { $in: criteriaTypes } }).snapshot().forEach(function (item) {
        item.CriteriaEntity = null;
        item.CriteriaEntityField = getCriteriaEntityField(item);
        collection.save(item);
    });
});

function getNewTemplateCriteria(groupCountEntity) {
    return {
        'Name': groupCountEntity.name,
        'CriteriaEntity': null,
        'CriteriaEntityField': groupCountEntity.name,
        'CriteriaType': groupCountEntity.criteriaType,
        'CriteriaLevel2Id': NUUID('00000000-0000-0000-0000-000000000000'),
        'CriteriaLevel3Id': NUUID('00000000-0000-0000-0000-000000000000'),
        'IsScreenable': true
    };
}

var groupCountEntities = [
    { id: NUUID('2cbe8eb5-4ec8-c1e1-5f8b-592d00100fb1'), name: 'CG - Rank - GroupCount', criteriaType: 16 },
    { id: NUUID('8ec94c4f-d14f-0caa-8b21-6e5c4fd7ea4b'), name: 'Environment Rank - GroupCount', criteriaType: 6 },
    { id: NUUID('88bd71ee-e715-c176-aadf-c9545af38af3'), name: 'Governance Rank - GroupCount', criteriaType: 6 },
    { id: NUUID('6326f6fc-c645-4dbc-1a3d-ec8c6ee351aa'), name: 'Rank - GroupCount', criteriaType: 6 },
    { id: NUUID('81c8f2ff-d5d5-9027-69c2-34dcffeabb17'), name: 'Social Rank - GroupCount', criteriaType: 6 },
];

groupCountEntities.forEach(function (item) {
    db.TemplateCriteria.update({ _id: item.id }, getNewTemplateCriteria(item), { upsert: true });
});

db.TemplateCriteria.remove({ Name: 'CG - Rank - CompaniesCount' });
